package com.example.finger.dialog;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.finger.FingerHelper;
import com.example.finger.R;
import com.example.finger.SerialPortUtil;
import com.example.finger.bean.SoketOrder;
import com.example.finger.bean.TaskWithPadlock;
import com.example.finger.rules.FingerLib;
import com.example.finger.socket.SoketUploadData;
import com.example.finger.util.MatchFinger;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lyxmaster.lib.toasty.Toasty;
import com.lyxmaster.lib.util.DataConfig;
import com.lyxmaster.lib.util.FileUtils;
import com.lyxmaster.lib.view.BaseActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by LU-MAC on 2018/12/22.
 */

public class ChangePwdDialog extends BaseDialog {
    public TextView textViewTip;
    public TextView textViewTitle;
    private FingerLib m_szHost = FingerHelper.getInStance().m_szHost;
    private Context context;

    private int order = 0;
    private final int CLEANFINGER = 1;
    private final int INPUTMANAGER = 2;
    private final int EQUESEFINGER = 3;
    private int fingerIndex = 0;

    private String lockId = "";

    private boolean BChange = false;

    private List<String> FingerData = new ArrayList<>();


    @Override
    public View createView(Context context, LayoutInflater inflater, ViewGroup container) {
        super.createView(context,inflater,container);
        this.context = context;
        return inflater.inflate(R.layout.dialog_changpwd, container, false);
    }

    public static ChangePwdDialog getInstance(String title) {
        ChangePwdDialog dialogFragment = new ChangePwdDialog();
        dialogFragment.setCanceledBack(false);
        dialogFragment.setCanceledOnTouchOutside(false);

        Bundle args = new Bundle();
        args.putString("title", title);
        dialogFragment.setArguments(args);

        return dialogFragment;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

//        FingerData = new Gson().fromJson(getArguments().getString("title"), new TypeToken<List<String>>(){}.getType());
        FingerData = new Gson().fromJson(FileUtils.getFileContent(new File(FingerHelper.TASTDIR+FingerHelper.MANAFIGER)), new TypeToken<List<String>>(){}.getType());

        lockId = getArguments().getString("title");

        textViewTip = getView().findViewById(R.id.tv_tip);
        textViewTitle = getView().findViewById(R.id.tv_title);
        textViewTitle.setText("密码更新");
        textViewTip.setText("正在初始化");

        getView().findViewById(R.id.tv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        order = CLEANFINGER;

        SerialPortUtil.getInstance().setSCMDataReceiveListener(new SerialPortUtil.SCMDataReceiveListener() {
            @Override
            public void dataRecevie(final byte[] data) {
                ((Activity)(context)).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            byte[] num = new byte[8];
                            System.arraycopy(data, 3, num, 0, 8);
                            textViewTitle.setText("密码更新 " + new String(num, "US-ASCII"));

                            char[] suogan = DataConfig.invertUsingFor(DataConfig.bytes2BinaryStr(new byte[]{data[24]}).toCharArray());
                            if(BChange){
                                if(suogan[1]=='1'){
                                    Toasty.success(context, "修改密码成功").show();
                                    dismiss();
                                }
                                if(suogan[2]=='1'){
                                    Toasty.error(context, "修改密码失败").show();
                                    dismiss();
                                }
                            }


                            resetTimer();
                        }
                        catch (Exception e) {
                            Toasty.success(context, e.getMessage()).show();
                        }
                    }
                });
            }
        });

        m_szHost.setOnFingerDoneListener(new FingerLib.OnFingerDoneListener() {
            @Override
            public void OnGetMessage(String content) {
                switch (order){
                    case CLEANFINGER:
//                        downLoadManageFInger();
                        order = EQUESEFINGER;
                        textViewTip.setText("请按下管理员指纹");
                        m_szHost.Run_CmdGetFeatureOfCapturedFP();
                        break;
                    case EQUESEFINGER:
                        if(content.startsWith("0")){
                            for(int i=0; i<FingerData.size(); i++){
                                DataConfig.hexStringToHexBytes(FingerData.get(i));
                                if(MatchFinger.match(DataConfig.hexStringToHexBytes(FingerData.get(i)), m_szHost.m_TemplateData)){
                                    Toasty.success(context, "匹配成功").show();
                                    textViewTip.setText("正在更新密码");
                                    try {
                                        BChange = true;
                                        FingerHelper.getInStance().changPwd(null,textViewTitle.getText().toString().split(" ")[1]);
                                    } catch (Exception e) {
                                        Toasty.success(context, e.getMessage()).show();
                                    }
                                    return;
                                }
                            }
                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    ((Activity)(context)).runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            order = EQUESEFINGER;
                                            textViewTip.setText("请按下管理员指纹");
                                            m_szHost.Run_CmdGetFeatureOfCapturedFP();
                                            Toasty.error(context, "匹配失败").show();
                                        }
                                    });
                                }
                            }, 1000);

                        }else {
                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    ((Activity)(context)).runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            textViewTip.setText("获取失败,请再按一次");
                                            order = EQUESEFINGER;
                                            m_szHost.Run_CmdGetFeatureOfCapturedFP();
                                        }
                                    });
                                }
                            }, 1000);
                        }
                        break;
                }
            }
        });

        m_szHost.Run_CmdDeleteAll();
    }

    private Timer timerBtRecv = new Timer();
    private TimerTask timerTaskBtRecv;
    private void resetTimer(){
        if(timerTaskBtRecv != null) timerTaskBtRecv.cancel();
        timerTaskBtRecv = new TimerTask() {
            @Override
            public void run() {
                try {
                    ((Activity)(context)).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textViewTip.setText("");
                        }
                    });
                }catch (Exception e){

                }
            }
        };
        timerBtRecv.schedule(timerTaskBtRecv, 1000);
    }

//    @Override
//    public void onDestroy(){
//        super.onDestroy();
//        m_szHost.setOnFingerListener(null);
//        m_szHost.setOnFingerDoneListener(null);
//        try{
//            m_szHost.Run_CmdCancel();
//        }catch(Exception e) {}
//    }

    @Override
    public void dismiss(){
//        bShow = false;
        ((BaseActivity)(context)).hud.show("正在退出操作");
//        m_szHost.setOnFingerListener(null);
//        m_szHost.setOnFingerDoneListener(null);
////        m_szHost.setOnFingerDoneListener(new FingerLib.OnFingerDoneListener() {
////            @Override
////            public void OnGetMessage(String content) {
////                ((BaseActivity) (context)).hud.dismiss();
////                m_szHost.setOnFingerDoneListener(null);
////                DownLoadDialog.super.dismiss();
////            }
////        });
//        m_szHost.Run_CmdCancel();
//        new Timer().schedule(new TimerTask() {
//            @Override
//            public void run() {
//                ((Activity)(getContext())).runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        ((BaseActivity) (context)).hud.dismiss();
//                        ChangePwdDialog.super.dismiss();
//                    }
//                });
//            }
//        },2000);
        SerialPortUtil.getInstance().setSCMDataReceiveListener(null);
        m_szHost.setOnFingerListener(null);
        m_szHost.setOnFingerDoneListener(null);
        m_szHost.Run_CmdCancel();
        if(timerTaskBtRecv != null) timerTaskBtRecv.cancel();
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                ((Activity)(getContext())).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((BaseActivity) (context)).hud.dismiss();
                        ChangePwdDialog.super.dismiss();
                    }
                });
            }
        },2000);
    }
}